package top.someapp.applib.kits;

import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 线程执行帮助类，在android中某些操作要求在UiThread(主线程)中，某些操作不能在UiThread中
 * 该类可以方便地指定操作是否在主线程中执行
 *
 * @author zwz
 * Created on 2019-11-09
 */
public class TaskExecutors {

    private final Executor mUiThread;
    private final Executor mDiskIO;
    private final Executor mNetworkIO;

    protected TaskExecutors(Executor mUiThread, Executor mDiskIO, Executor mNetworkIO) {
        this.mUiThread = mUiThread;
        this.mDiskIO = mDiskIO;
        this.mNetworkIO = mNetworkIO;
    }

    public TaskExecutors() {
        this(new UiThreadExecutor(), Executors.newSingleThreadExecutor(),
            Executors.newFixedThreadPool(3));
    }

    public Executor diskIO() {
        return mDiskIO;
    }

    public Executor networkIO() {
        return mNetworkIO;
    }

    public Executor uiThread() {
        return mUiThread;
    }

    private static class UiThreadExecutor implements Executor {

        private Handler uiThreadHandler = new Handler(Looper.getMainLooper());

        @Override
        public void execute(Runnable command) {
            uiThreadHandler.post(command);
        }
    }

}
